package com.qf.service.impl;

import com.qf.Utils.Json;
import com.qf.entity.Goods;
import com.qf.service.SearchService;
import com.qf.vo.Param;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/12/21:06
 * @Description:
 */
@Service
public class SearchServiceimpl implements SearchService {
    private String index="shop-project";
    private String type="shopProjectType";
    @Autowired
    private RestHighLevelClient client;
    @Override
    public void add(Goods goods) throws Exception {
        IndexRequest request = new IndexRequest(index,type);
        request.source(Json.toJSON(goods), XContentType.JSON);
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        System.out.println(index.toString());
    }

    @Override
    public List<Goods> getGoodsList(Param param) throws IOException {
        List<Goods> goodsList=new ArrayList<>();
        SearchRequest request = new SearchRequest();
        request.indices(index).types(type);
        SearchSourceBuilder builder = new SearchSourceBuilder();
         //设置高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("gname")
                .preTags("<font color='red'>")
                .postTags("</font>");
        builder.highlighter(highlightBuilder);

        //排序
        if(param.getOrderFiled()!=null){
            switch (param.getOrderFiled()){
                case 1:
                    builder.sort("id", SortOrder.DESC);
                    break;
                case 2:
                    builder.sort("gprice", SortOrder.DESC);
                    break;
                case 3:
                    builder.sort("gtypePid", SortOrder.DESC);
                    break;

            }

        }
        request.source(builder);
  if(!StringUtils.isEmpty(param.getKeyword())){
      request.source().query(QueryBuilders.multiMatchQuery(param.getKeyword(),"gname","gdesc"));
  }
  if (param.getType()!=null){
      request.source().query(QueryBuilders.termQuery("gtypeCid",param.getType()));
  }
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
      //将json转化成goods
        Goods goods=null;
        SearchHit[] hits = response.getHits().getHits();
        for (int i = 0; i < hits.length; i++) {
              SearchHit  hit=hits[i];
            Map<String, Object> map = hit.getSourceAsMap();
             goods= new Goods();
            try {
                BeanUtils.populate(goods,map);
                HighlightField gname = hit.getHighlightFields().get("gname");
                if(gname!=null){
                    String s = gname.getFragments()[0].toString();
                    goods.setGname(s);
                }
                goodsList.add(goods);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return goodsList;
    }

}
